"""
微信视频号直播服务实现
"""
import json
import threading
import requests
import sys
from app.utils.logger import Logger
from .wx_event_handler import WXLiveEventHandler
# 导入消息处理器
import time
from app.services.message_processor import MessageProcessor

# 控制台颜色常量
class ConsoleColors:
    """控制台颜色定义"""
    HEADER = '\033[95m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    PURPLE = '\033[35m'
    CYAN = '\033[36m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    END = '\033[0m'

class WXLiveService(WXLiveEventHandler):
    """微信直播服务，实现事件处理接口"""
    
    def __init__(self, config):
        """
        初始化服务
        
        @param config: WXLiveConfig 配置对象
        """
        self.config = config
        self.logger = Logger.get_logger("wx_live_service")
        self.events_lock = threading.Lock()
        self.live_info = {}
        self.recent_events = []  # 保存最近的事件，用于UI显示
        self.max_recent_events = 100
        self.observers = []  # 观察者列表，用于通知UI更新
        self.console_output = True  # 是否输出到控制台
        self.send_to_processor = True  # 是否发送到消息处理器
        
    def set_console_output(self, enabled):
        """
        设置是否输出到控制台
        
        @param enabled: 是否启用
        """
        self.console_output = enabled
        
    def _print_to_console(self, message, color=None):
        """
        打印消息到控制台
        
        @param message: 要打印的消息
        @param color: 颜色代码
        """
        if not self.console_output:
            return
            
        try:
            if color:
                print(f"{color}{message}{ConsoleColors.END}")
            else:
                print(message)
            sys.stdout.flush()  # 确保立即输出
        except Exception as e:
            self.logger.error(f"输出到控制台时发生错误: {str(e)}")
        
    def add_observer(self, callback):
        """
        添加观察者
        
        @param callback: 回调函数，接收事件类型和数据
        """
        if callback not in self.observers:
            self.observers.append(callback)
            
    def remove_observer(self, callback):
        """
        移除观察者
        
        @param callback: 要移除的回调函数
        """
        if callback in self.observers:
            self.observers.remove(callback)
            
    def notify_observers(self, event_type, data):
        """
        通知所有观察者
        
        @param event_type: 事件类型
        @param data: 事件数据
        """
        for callback in self.observers:
            try:
                callback(event_type, data)
            except Exception as e:
                self.logger.error(f"通知观察者时发生错误: {str(e)}")
    
    def on_status_update(self, live_info):
        """
        处理直播状态更新
        
        @param live_info: 直播信息
        """
        self.live_info.update(live_info)
        
        # 输出到控制台
        live_status = live_info.get("live_status", 0)
        status_text = "直播中" if live_status == 1 else "未开播" if live_status == 0 else "未知"
        
        # 兼容性处理：同时更新status字段，保持向后兼容
        if "status" not in live_info and "live_status" in live_info:
            live_info["status"] = live_info["live_status"]
            
        view_count = live_info.get("view_count", live_info.get("online_count", 0))
        like_count = live_info.get("like_count", 0)
        
        status_color = ConsoleColors.GREEN if live_status == 1 else ConsoleColors.YELLOW if live_status == 0 else ConsoleColors.BLUE
        
        # self._print_to_console("=" * 50, ConsoleColors.BOLD)
        # self._print_to_console(f"[直播状态] {status_text}", status_color)
        # self._print_to_console(f"[观众数量] {view_count}", ConsoleColors.CYAN)
        # self._print_to_console(f"[点赞数量] {like_count}", ConsoleColors.PURPLE)
        # self._print_to_console("=" * 50, ConsoleColors.BOLD)
        
        # 发送到消息处理器
        if self.send_to_processor:
            try:
                # 获取消息处理器实例
                processor = MessageProcessor.get_instance()
                
                # 构建状态消息
                message = {
                    "type": "live_status",
                    "timestamp": int(time.time()),
                    "live_status": live_status,
                    "status_text": status_text,
                    "view_count": view_count,
                    "like_count": like_count,
                    "title": live_info.get("title", "")
                }
                
                # 发送到消息处理器
                message_id = processor.process_message(message, "wechat_channel")
                if message_id:
                    self.logger.debug(f"视频号直播状态已发送到消息处理器，消息ID: {message_id}")
                    
            except Exception as e:
                self.logger.error(f"发送视频号直播状态到消息处理器时出错: {str(e)}")
        
        # 通知观察者
        self.notify_observers("status_update", live_info)
        
        # 转发状态到指定URL
        self._forward_data({"type": "status", "data": live_info})
        
    def on_events(self, data):
        """
        处理直播事件
        
        @param data: 事件数据
        """
        events = data.get("events", [])
        if not events:
            return
            
        # 添加到最近事件列表
        with self.events_lock:
            for event in events:
                self.recent_events.append(event)
                # 限制最近事件数量
                if len(self.recent_events) > self.max_recent_events:
                    self.recent_events.pop(0)
                    
        # 记录事件并输出到控制台
        for event in events:
            event_name = event.get("event_name", "unknown")
            user_name = event.get("user", {}).get("nickname", "未知用户")
            
            # 转换事件格式为消息处理器格式并发送
            if self.send_to_processor:
                self._send_to_message_processor(event)
            
            if event_name == "comment":
                content = event.get("content", "")
                self.logger.info(f"收到弹幕: {user_name} - {content}")
                self._print_to_console(f"[弹幕] {user_name}: {content}", ConsoleColors.GREEN)
                
            elif event_name == "gift":
                gift_name = event.get("gift_name", "未知礼物")
                gift_count = event.get("gift_count", 1)
                self.logger.info(f"收到礼物: {user_name} 赠送了 {gift_count} 个 {gift_name}")
                self._print_to_console(f"[礼物] {user_name} 赠送了 {gift_count} 个 {gift_name}", ConsoleColors.RED)
                
            elif event_name == "join":
                self.logger.info(f"用户进入: {user_name}")
                self._print_to_console(f"[进入] {user_name} 进入了直播间", ConsoleColors.BLUE)
                
            elif event_name == "like":
                like_count = event.get("like_count", 1)
                self.logger.info(f"收到点赞: {user_name} 点赞了 {like_count} 次")
                self._print_to_console(f"[点赞] {user_name} 点赞了 {like_count} 次", ConsoleColors.YELLOW)
                
            elif event_name == "follow":
                self.logger.info(f"收到关注: {user_name} 关注了主播")
                self._print_to_console(f"[关注] {user_name} 关注了主播", ConsoleColors.PURPLE)
                
        # 通知观察者
        self.notify_observers("events", events)
        
        # 转发事件到指定URL
        self._forward_data({"type": "events", "data": events})
    
    def _send_to_message_processor(self, event):
        """
        将事件转换为标准格式并发送到消息处理器
        
        @param event: 视频号事件
        """
        try:
            # 获取消息处理器实例
            processor = MessageProcessor.get_instance()
            
            # 转换事件格式 - 修复：使用decoded_type字段而不是event_name字段
            event_type = event.get("decoded_type", "unknown")
            timestamp = int(time.time())  # 使用当前时间戳
            
            # 记录准备处理的原始事件
            self.logger.info(f"准备发送到处理器的视频号事件: {json.dumps(event, ensure_ascii=False)}")
            
            # 提取用户名
            nickname = event.get("nickname", "未知用户")
            
            # 构建标准消息格式，添加user_name字段
            message = {
                "timestamp": timestamp,
                "user_id": event.get("sec_openid", ""),
                "nickname": nickname,
                "user_name": nickname,  # 添加user_name字段，确保兼容性
                "platform": "wechat_channel"  # 明确设置平台
            }
            
            # 根据事件类型设置不同的消息字段
            if event_type == "comment":
                message["type"] = "comment"
                message["content"] = event.get("content", "")
                
            elif event_type == "gift":
                message["type"] = "gift"
                message["gift_id"] = event.get("gift_id", "")
                # 添加content字段，优先使用event中的content
                content = event.get("content", "")
                message["content"] = content
                
            elif event_type == "join":
                message["type"] = "join"
                message["join_time"] = timestamp
                
            elif event_type == "like":
                message["type"] = "like"
                message["like_count"] = event.get("like_count", 1)
                
            elif event_type == "follow":
                message["type"] = "follow"
                message["follow_time"] = timestamp
            
            else:
                # 未知事件类型，跳过处理
                self.logger.warning(f"未知事件类型: {event_type}，跳过处理")
                return
            
            # 记录转换后的标准格式消息
            self.logger.info(f"转换后的标准消息: {json.dumps(message, ensure_ascii=False)}")
            
            # 发送到消息处理器
            message_id = processor.process_message(message, "wechat_channel")
            if message_id:
                self.logger.info(f"视频号消息已发送到消息处理器，消息ID: {message_id}")
            else:
                self.logger.warning("消息处理器返回空ID，消息可能被过滤或处理失败")
            
        except ImportError as ie:
            self.logger.error(f"消息处理器不可用，导入错误: {str(ie)}")
            self.send_to_processor = False  # 关闭发送功能
        except Exception as e:
            self.logger.error(f"发送视频号消息到消息处理器时出错: {str(e)}")
            import traceback
            self.logger.error(f"异常堆栈: {traceback.format_exc()}")
    
    def _forward_data(self, data):
        """
        转发数据到指定URL
        
        @param data: 要转发的数据
        """
        forward_url = self.config.get_prop("forward_url")
        if not forward_url:
            return
            
        try:
            # 使用非阻塞方式发送请求
            threading.Thread(
                target=self._send_request, 
                args=(forward_url, data), 
                daemon=True
            ).start()
        except Exception as e:
            self.logger.error(f"创建转发线程失败: {str(e)}")
    
    def _send_request(self, url, data):
        """
        发送HTTP请求
        
        @param url: 目标URL
        @param data: 请求数据
        """
        try:
            headers = {
                "Content-Type": "application/json",
                "User-Agent": "WXLiveSpy/1.0"
            }
            response = requests.post(
                url, 
                json=data,
                headers=headers,
                timeout=5
            )
            
            if response.status_code == 200:
                self.logger.debug(f"数据转发成功: {url}")
            else:
                self.logger.warning(f"数据转发失败: HTTP {response.status_code}")
                
        except requests.RequestException as e:
            self.logger.error(f"数据转发请求异常: {str(e)}")
    
    def get_live_info(self):
        """
        获取当前直播信息
        
        @return: 直播信息字典
        """
        return self.live_info
    
    def get_recent_events(self):
        """
        获取最近的事件
        
        @return: 事件列表
        """
        with self.events_lock:
            return list(self.recent_events) 